package com.example.lotapp;

import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import org.json.JSONArray;
import org.json.JSONObject;
import org.json.JSONTokener;

import android.app.Service;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;

import com.example.lotapp.dataAdapter.FootballDataHelper;
import com.example.lotapp.network.HttpUtils;
import com.example.lotapp.tasks.AsynServerBaseTask;
import com.example.lotapp.utils.ServerJsonParser;

public class MainService extends Service {

	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		return super.onStartCommand(intent, Service.START_STICKY, startId);
	}

	private static final int LOT_FOOTBALL_RESULT = 1;
	private static final int LOT_FOOTBALL_ORIGIN = 2;
	

	private static String mServerUrl = "http://10.20.240.151/api/handle_post.php";
	
	private Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case LOT_FOOTBALL_RESULT:
				fetchFootballIssue();
				break;
			case LOT_FOOTBALL_ORIGIN:
				break;
			}
			super.handleMessage(msg);
		}
	};
	
	@Override
	public void onCreate() {
		super.onCreate();
		
		TimerTask task = new TimerTask() {
			@Override
			public void run() {
				mHandler.sendEmptyMessage(LOT_FOOTBALL_RESULT);
				mHandler.sendEmptyMessage(LOT_FOOTBALL_ORIGIN);
			}
		};
		
		Timer timer = new Timer();
		timer.schedule(task, 10, 1000 * 10);
	}
	
	@Override
	public void onDestroy() {
		super.onDestroy();
	}
	
	public static void start() {
		AppContext.getInstance().startService(new Intent(AppContext.getInstance(), MainService.class));
	}

	public static void stop() {
		AppContext.getInstance().stopService(new Intent(AppContext.getInstance(), MainService.class));
	}
	
	private void fetchFootballIssue() {
		JSONObject jsonObject = new JSONObject();
		try {
			jsonObject.put("LottID", "90");
		} catch (Exception e) {
		}
		
		new AsynServerBaseTask("313") {
			@Override
			protected void onPostExecute(String result) {
				try {
					JSONTokener jsonParser = new JSONTokener(result);
					JSONObject js = (JSONObject) jsonParser.nextValue();
					if (Integer.parseInt(js.getString("Code")) == 0) {
						String str = js.getString("Data");
						JSONObject js2 = new JSONObject(str);
						List<Map<String, Object>> list = ServerJsonParser.getList(js2.getString("item"));
						if (list != null && list.size() > 0) {
							for (int i = 0; i < list.size(); ++i) {
								fetchFootballResult(1, list.get(i).get("IssueID").toString());
							}
						}
					}
				} catch (Exception e) {
				}
		    }
		}.execute(jsonObject.toString());
	}
	
	private void fetchFootballResult(final int pageNum, final String issueId) {
		JSONObject jsonObject = new JSONObject();
		try {
			jsonObject.put("IssueID", issueId);
			jsonObject.put("PageNo", pageNum);
			jsonObject.put("PageSize", 100);
		} catch (Exception e) {
		}
		
		new AsynServerBaseTask("310") {
			@Override
			protected void onPostExecute(String result) {
				try {
					JSONTokener jsonParser = new JSONTokener(result);
					JSONObject js = (JSONObject) jsonParser.nextValue();
					if (Integer.parseInt(js.getString("Code")) == 0) {
						String str = js.getString("Data");
						JSONObject js3 = new JSONObject(str);
						int totalNum = Integer.valueOf(js3.getString("Count"));
						List<Map<String, Object>> list = ServerJsonParser.getList(js3.getString("item"));
						postFootballResult(list);
						if (totalNum > pageNum * 100) {
							fetchFootballResult(pageNum + 1, issueId);
						}
					}
				} catch (Exception e) {
				}
		    }
		}.execute(jsonObject.toString());
	}
	
	private void postFootballResult(List<Map<String, Object>> list) {
		if (list == null || list.size() == 0) {
			return ;
		}
		
		try {
			JSONArray jsonArray = new JSONArray();
			for (int i = 0; i < list.size(); ++i) {
				String matchId = list.get(i).get("MNo").toString();
				String score = list.get(i).get("Score").toString();
				String helfScore = list.get(i).get("Hrz").toString();
				long scoreInt64 = FootballDataHelper.makeScoreBitData(score, helfScore);
				JSONObject jsonObject = new JSONObject();
				jsonObject.put(FootballDataHelper.getAdaptKey("MNo"), matchId);
				jsonObject.put(FootballDataHelper.getAdaptKey("Score"), scoreInt64);
				jsonArray.put(jsonObject);
			}
			
			final String paramStr = "action=1&params=" + jsonArray.toString();
			new AsyncTask<String, Integer, String>() {
				@Override
				protected String doInBackground(String... params) {
					try {
						return HttpUtils.post(mServerUrl, paramStr, null);
					} catch (Exception e) {
						return null;
					}
				}
				@Override
				protected void onPostExecute(String result) {
					Log.d("postToServer", result + "");
				}
			}.execute("");
		} catch (Exception e) {
		}
	}
}
